import React from 'react';
import { connect } from 'dva';
import _ from 'lodash';
import * as authService from '../services/authService';
import Login from '../routes/LoginPage';
import Home from '../routes/HomePage';
import { Toast } from "antd-mobile";

class EnsureLoggedInContainer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isCheck: false,
      isLogin: false,
      message: '',
    };
  }

  componentDidMount() {
    if (this.props.location.pathname !== '/login') {
      authService.me().then((data) => {
        if (_.get(data, 'data.shopId')) {
          if (_.get(data, 'data.status') === 1) {
            this.setState({
              message: '账号已禁用！',
            });
            // return;
          } else {
            this.props.dispatch({ type: 'auth/loginSuccess', payload: data.data });
          }
        } else {
          this.props.history.replace({
            pathname: '/login',
          });
        }
      }).catch(() => {
        this.props.history.replace({
          pathname: '/login',
        });
      });
    }
  }

  render() {
    if (this.props.isLogin) {
      if (this.props.location.pathname === '/') {
        return <Home />;
      }
      return this.props.children;
    }
    if (this.state.message) {
      return <h3 style={{ textAlign: 'center' }}>{this.state.message}</h3>;
    }
    return <Login />;
  }
}

function mapStateToProps(state, props) {
  return {
    isLogin: state.auth.currentUser.shopId,
  };
}

export default connect(mapStateToProps)(EnsureLoggedInContainer);
